package sapling.api;

import com.httpclient.HttpClientUtil;
import com.httpclient.common.HttpConfig;
import com.httpclient.common.HttpHeader;
import com.httpclient.common.HttpMethods;
import com.httpclient.exception.HttpProcessException;
import io.swagger.annotations.ApiOperation;
import org.apache.http.Header;
import org.apache.http.util.TextUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import sapling.dao.BatchDao;
import sapling.dao.LandMassDao;
import sapling.dao.TreeDao;
import sapling.model.Batch;
import sapling.model.LandMass;
import sapling.model.Tree;
import sapling.service.AreaLocationService;
import sapling.utils.Md5Util;
import sapling.utils.Msg;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by mac on 17/7/11.
 */
@RestController
@RequestMapping("/api/batch")
public class BatchApi {
    @Autowired
    TreeDao treeDao;
    @Autowired
    BatchDao batchDao;
    @Autowired
    AreaLocationService areaLocationService;
    @Autowired
    LandMassDao landMassDao;

    @ApiOperation(value = "生成批次", notes = "生成批次")
    @PostMapping("/generate")
    public Msg<Object> list(@RequestParam String treeids){
        if(!TextUtils.isEmpty(treeids)) {
            String res = treeids.substring(0, treeids.length() - 1);
            Batch batch=new Batch();
            int sumnumber=0;
            double price=0;
            for(String treeid:res.split(";")){
                long id = Long.parseLong(treeid);
                Tree tree = treeDao.findOne(id);
                String serialNumber = tree.getSerialNumber();
                List<Tree> serialnumbertrees = treeDao.findSerialnumber(serialNumber);
                for(Tree tr:serialnumbertrees){
                    tr.setResponseState(1);
                    treeDao.saveAndFlush(tr);
                }
                tree.setResponseState(1);
                treeDao.saveAndFlush(tree);
                sumnumber+=tree.getNumber();
                batch.getTrees().add(tree);
                price+=tree.getPrice()*tree.getNumber();
                batch.setLocation(tree.getLocation());
                batch.setStandard(tree.getTreeSpecies());
                batch.setSingleprice(tree.getPrice());
                LandMass landMass= landMassDao.findOne(tree.getLandmassid());
                if(Objects.nonNull(landMass)){
                    batch.setLandmass(landMass.getAreaLocation().getSerialNumber()+landMass.getSerialNumber());
                }
            }
            batch.setPrice(price);
            batch.setBatchNumber(UUID.randomUUID().toString());
            batch.setNumber(sumnumber);
            Batch save = batchDao.save(batch);
            SimpleDateFormat smp=new SimpleDateFormat("yyyyMMdd");
            String batchNumber=smp.format(new Date());
            batchDao.saveAndFlush(save);
        }
        return Msg.newMsg(true);
    }

    @Scheduled(cron="0 0 2 * * ?")//每天2点执行
    @ApiOperation(value = "自动生成批次", notes = "自动生成批次")
    @PostMapping("/generateBatch")
    public Msg<Object> list(){
        List<Tree> willGenerBatchTrees = treeDao.findWillGenerBatch();
        for(Tree tree:willGenerBatchTrees){
            int month =tree.getCreatetime().getYear()*12+tree.getCreatetime().getMonth();
            List<Batch> batchlist = batchDao.findOnebatch(month, tree.getTreeSpecies(), tree.getLocation(), tree.getHeight(), tree.getChestBreadth(), tree.getCrownWidth());
            if(batchlist!=null&&batchlist.size()>0){
                tree.setBatch(batchlist.get(0));
                Batch save = batchlist.get(0);
                save.setNumber(save.getNumber()+1);
                batchDao.saveAndFlush(save);
            }else{
                Batch batch = new Batch();
                batch.setCrownwidth(tree.getCrownWidth());
                batch.setSingleprice(tree.getPrice());
                batch.setStandard(tree.getTreeSpecies());
                batch.setChestbreadth(tree.getChestBreadth());
                batch.setCrownwidth(tree.getCrownWidth());
                batch.setClump(tree.getClump());
                batch.setMonth(month);
                batch.setLocation(tree.getLocation());
                batch.setHeight(tree.getHeight());
                batch.setSalenumber(tree.getSalenumber());
                Batch save = batchDao.save(batch);
                tree.setBatch(save);
                SimpleDateFormat smp=new SimpleDateFormat("yyyyMMdd");
                String batchNumber=smp.format(new Date());
                save.setBatchNumber(batchNumber+save.getBatch_id());
                save.setNumber(save.getNumber()+1);
                batchDao.saveAndFlush(save);
            }
            tree.setResponseState(1);
            treeDao.saveAndFlush(tree);
        }
        return Msg.newMsg(true);
    }

   /* @Scheduled(cron = "0 15 2 * * ?" )
    @ApiOperation(value = "定时修改批次",notes = "具体修改参数可调")
    @PostMapping("/timing/update")
    public void timingUpdate(){
        for (Batch bar:batchDao.findHavebatch()) {
            for (Tree tree:bar.getTrees()) {
                tree.setHeight(tree.getHeight()+1);
                tree.setCrownWidth(tree.getCrownWidth()+1);
                tree.setChestBreadth(tree.getChestBreadth()+1);
                if(tree.getClump()){//丛生则枝条数增加
                    tree.setSalenumber(tree.getSalenumber()+1);
                }
                treeDao.save(tree);
            }
        }
    }*/

    @ApiOperation(value = "录入价格和产地", notes = "苗木的treeids无论多个或一个在id后面加上分号,price 价格，产地location")
    @PostMapping("/update")
    public Msg<Object> list(@RequestParam String treeids,@RequestParam double price,@RequestParam String location){
        if(!TextUtils.isEmpty(treeids)) {
            String res = treeids.substring(0, treeids.length() - 1);
            for(String treeid:res.split(";")){
                long id = Long.parseLong(treeid);
                Tree tree = treeDao.findOne(id);
                if(Objects.nonNull(tree)){
                    String serialNumber = tree.getSerialNumber();
                    List<Tree> serialnumbertrees = treeDao.findSerialnumber(serialNumber);
                    for(Tree tr:serialnumbertrees){
                        tr.setPrice(price);
                        tr.setLocation(location);
                       // tr.setResponseState(1);
                        treeDao.saveAndFlush(tr);
                    }
                }
            }
        }
        return Msg.newMsg(true);
    }
    @ApiOperation(value ="短信",notes = "短信")
    @GetMapping("/send")
    public String send(@RequestParam String phone){
        /**
         *  "Accept": "application/json;charset=UTF-8",
         "x-credential-username": "verificationCode"
         */
        HttpConfig conf = HttpConfig.custom().url("http://ytxny.yutong.com/platform/thirdVerification/getVerificationCode?phone="+phone);
        Header[] head = HttpHeader.custom().other("Accept", "application/json;charset=UTF-8").other("x-credential-username","verificationCode").build();
        conf.method(HttpMethods.GET);
        conf.headers(head);
        String resp = null;
        try {
            resp = HttpClientUtil.send(conf);
        } catch (HttpProcessException e) {
            e.printStackTrace();
        }
        System.out.println("请求结果内容："+ resp);
        return resp;
    }
    @ApiOperation(value ="校验短信",notes = "校验短信")
    @PostMapping("/check")
    public String check(@RequestParam String phone,@RequestParam String code){
        /**
         *  "Accept": "application/json;charset=UTF-8",
         "x-credential-username": "verificationCode"
         */
        HttpConfig conf = HttpConfig.custom().url("http://ytxny.yutong.com/platform/thirdVerification/vaildVerificationCode");
        Header[] head = HttpHeader.custom().other("Accept", "application/json;charset=UTF-8").other("x-credential-username","verificationCode").build();
        conf.method(HttpMethods.POST);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("checkCode","{\"phone\":\""+phone+"\",\"code\":\""+code+"\"}");
        conf.map(map);
        conf.headers(head);
        String resp = null;
        try {
            resp = HttpClientUtil.send(conf);
        } catch (HttpProcessException e) {
            e.printStackTrace();
        }
        System.out.println("请求结果内容："+ resp);
        return resp;
    }
    @GetMapping("/gettoken")
    public String gettoken(){
        String channelType="WYKJ";
        long timestamp=new Date().getTime();
        String signate="";
        try {
            String encode = URLEncoder.encode(channelType + channelType + timestamp + "yutongkey", "utf-8").toUpperCase();
            signate = Md5Util.getMd5(encode);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        HttpConfig conf = HttpConfig.custom().url("http://wx.yutong.com/thtml/yutong/live800/getToken.thtml?channelType="+channelType+"&serviceAccount="+channelType+"&timestamp="+timestamp+"&signature="+signate);
//        Header[] head = HttpHeader.custom().other("Accept", "application/json;charset=UTF-8").other("x-credential-username","verificationCode").build();
        conf.method(HttpMethods.GET);
//        conf.headers(head);
        String resp = null;
        try {
            resp = HttpClientUtil.send(conf);
            JSONObject jobj=new JSONObject(resp);
            return jobj.optString("token");
        } catch (HttpProcessException e) {
            e.printStackTrace();
        }
        System.out.println("请求结果内容："+ resp);
        return resp;
    }

    @GetMapping("/getOpenid")
    public String getOpenid(){
        HttpConfig conf = HttpConfig.custom().url("https://api.weixin.qq.com/cgi-bin/user/get?access_token="+gettoken());
        conf.method(HttpMethods.GET);
        String resp = null;
        try {
            resp = HttpClientUtil.send(conf);
        } catch (HttpProcessException e) {
            e.printStackTrace();
        }
        System.out.println("请求结果内容："+ resp);
        return resp;
    }

    /**
     *  http请求方式: POST
     https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN
     {
     "touser":"wxc4d05db22e576d0a",
     "template_id":"Sm8xBXWZJKmMOMKuPFExKGEFezyNDadHwKLOYxI3IHs",
     "url":"http://weixin.qq.com/download",
     "miniprogram":{
     "appid":"xiaochengxuappid12345",
     "pagepath":"index?foo=bar"
     },
     "data":{
     "first": {
     "value":"恭喜你购买成功！",
     "color":"#173177"
     },
     "keynote1":{
     "DATA":"巧克力",
     "color":"#173177"
     },
     "keynote2": {
     "DATA":"39.8元",
     "color":"#173177"
     },
     "keynote3": {
     "DATA":"2014年9月22日",
     "color":"#173177"
     },
     "keynote4": {
     "DATA":"2014年9月23日",
     "color":"#173177"
     },
     "keynote5": {
     "DATA":"2014年9月24日",
     "color":"#173177"
     },
     "remark":{
     "value":"欢迎再次购买！",
     "color":"#173177"
     }
     }
     }

     */

    @ApiOperation(value ="发送模版消息",notes = "发送模版消息")
    @GetMapping("/sendtemplate")
    public String sendtemplate(@RequestParam(defaultValue = "oGFTtjrnyckYZoh1KLcF4GViGehc") String openid,@RequestParam String name,@RequestParam String pwd,@RequestParam String entername,@RequestParam String url){
        String token=gettoken();
        HttpConfig conf = HttpConfig.custom().url("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token);
        Header[] headers = HttpHeader.custom().contentType("application/json;charset=UTF-8").build();
        conf.headers(headers);
        conf.method(HttpMethods.POST);
        conf.json("{\"touser\":\"oGFTtjrnyckYZoh1KLcF4GViGehc\",\"template_id\":\"Sm8xBXWZJKmMOMKuPFExKGEFezyNDadHwKLOYxI3IHs\",\"url\":\"http://weixin.qq.com/download\",\"data\":{\"first\":{\"value\":\"尊敬的用户您好！\",\"color\":\"#173177\"},\"keynote1\":{\"value\":\""+name+"\",\"color\":\"#173177\"},\"keynote2\":{\"value\":\""+pwd+"\",\"color\":\"#173177\"},\"keynote3\":{\"value\":\""+entername+"\",\"color\":\"#173177\"},\"keynote4\":{\"value\":\""+url+"\",\"color\":\"#173177\"},\"keynote5\":{\"value\":\"400-659-6666\",\"color\":\"#173177\"},\"remark\":{\"value\":\"祝您使用愉快！\",\"color\":\"#173177\"}}}");
        String resp = null;
        try {
            resp = HttpClientUtil.send(conf);
        } catch (HttpProcessException e) {
            e.printStackTrace();
        }
        System.out.println("请求结果内容："+ resp);
        return resp;
    }

    @ApiOperation(value ="删除区域",notes = "删除区域")
    @GetMapping("/delarea")
    public String delarea(@RequestParam long areaid){
        areaLocationService.deleteArea(areaid);
        return "success";
    }

    @ApiOperation(value ="删除区域",notes = "删除区域")
    @GetMapping("/delareabyname")
    public String delarea(@RequestParam String name){
        areaLocationService.deleteAreabyname(name);
        return "success";
    }

    @ApiOperation(value ="删除地块",notes = "删除地块")
    @GetMapping("/delland")
    public String delland(@RequestParam long landid){
        areaLocationService.deleteLand(landid);
        return "success";
    }
    @ApiOperation(value = "获取区域地块",notes = "获取区域地块")
    @GetMapping("/getland")
    public List<LandMass> landMassList(@RequestParam long areaid){
        List<LandMass> area = landMassDao.findArea(areaid);
        return area;
    }

    @GetMapping("/clearland")
    public String clearland(@RequestParam long landid){
       areaLocationService.clearland(landid);
       return "success";
    }
}
